//
//  TTRecyclingListMyBuyViewCell.m
//  TaoTuo
//
//  Created by LG on 2020/9/5.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingListMyBuyViewCell.h"
#import "TTRecyclingCellTopView.h"
#import <UIImageView+WebCache.h>
#import "LLDateUtilis.h"
#import "TTLeadingLabelView.h"

@interface TTRecyclingListMyBuyViewCell ()

@property (nonatomic, strong) TTRecyclingCellTopView *topView;
@property (nonatomic, strong) UIImageView *leftImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *priceLabel;
/// 围观人数，竞价次数
@property (nonatomic, strong) UILabel *peopleLabel;
/// 成交时间，距离结束时间
@property (nonatomic, strong) UIButton *timeBtn;
/// 联系客服
@property (nonatomic, strong) UIButton *kefuBtn;
/// 查看详情
@property (nonatomic, strong) UIButton *detailBtn;

@property (nonatomic, strong) TTLeadingLabelView *labelView;

@property (nonatomic, strong) TTRecyclingListMyBuyModel *model;

@property (nonatomic, assign) CellType cellType;
@end


@implementation TTRecyclingListMyBuyViewCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.layer.cornerRadius = 8;

        [self setupSubviews];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyAction) name:@"recyclingMyBuyCellTimerNotify_key" object:nil];
    }
    return self;
}

- (void)notifyAction
{
    if (self.cellType == JingPai) {
        
        NSString *text = [NSString stringWithFormat:@"距离结束：%02ld:%02ld:%02ld", self.model.hour, self.model.minute, self.model.second];
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
        [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(DF2121) range:[attr.string rangeOfAll]];
        [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[text rangeOfString:@"距离结束："]];
        [self.timeBtn setAttributedTitle:attr forState:UIControlStateNormal];
        
    }
}


/// 联系客服
- (void)kefuBtnClick
{
    [[TTLoginSingle sharedSingle].loginModel.SalesmanMobile callPhone];
}
///  查看详情
- (void)detailBtnClick
{

}

- (void)setModel:(TTRecyclingListMyBuyModel *)model cellType:(CellType)cellType
{
    self.model = model;
    self.cellType = cellType;
    // 如果是购买，model.PayTime 和 model.Price 会有值
    
    NSString *imgName = @"";
    NSString *pricePrefix = @"价格：";
    if (model.SalesModel == 1) {
        imgName = @"询价";
    } else if (model.SalesModel == 2) {
        imgName = @"竞价";
        pricePrefix = model.PayTime.length > 0 ?  @"成交价：" : @"当前出价";
        
    } else if (model.SalesModel == 3) {
        imgName = @"一口价";
    }
    [self.topView setImageName:imgName title:model.SalesModel_Text];
    [self.leftImageView sd_setImageWithURL:[NSURL URLWithString:model.Picture] placeholderImage:[UIImage imageNamed:@"f_placeholder_img"] options:SDWebImageRetryFailed];
    self.titleLabel.text = model.Title;
    
    NSString *p = model.Price.length > 0 ? model.Price : model.Offer_Price;
    NSString *priceStr = [NSString stringWithFormat:@"%@￥%@", pricePrefix, p];
    NSMutableAttributedString *priceAttr = [[NSMutableAttributedString alloc] initWithString:priceStr];
    [priceAttr addAttributes:@{NSForegroundColorAttributeName : UIColorHex(#F22F3A), NSFontAttributeName : [UIFont boldSystemFontOfSize:9]} range:[priceStr rangeOfString:@"￥"]];
    [priceAttr addAttributes:@{NSForegroundColorAttributeName : UIColor.redColor, NSFontAttributeName : [UIFont boldSystemFontOfSize:18]} range:[priceStr rangeOfString:p]];
    self.priceLabel.attributedText = priceAttr;

    if (model.ReadingVolume > 0 || model.Goods_Offer_Count > 0) {
        self.peopleLabel.text = [NSString stringWithFormat:@"围观人数：%ld人    竞价次数：%ld次", model.ReadingVolume, model.Goods_Offer_Count];
    }

    if (cellType == JingPai) {
        // 竞拍
        [self handleJingpaiAction];
    } else {
        // 购买
        [self handleMyBuyAction];
    }

}

// 竞拍
- (void)handleJingpaiAction
{
    [self.timeBtn setImage:[UIImage imageNamed:@"naozhong"] forState:UIControlStateNormal];
    
    self.labelView.hidden = self.model.Price_Difference.length == 0;
    if (self.model.Price_Difference.intValue < 0) {
        NSString *t = [NSString stringWithFormat:@"已落后¥%d", ABS(self.model.Price_Difference.intValue)];
        [self.labelView setTitle:t titleColor:UIColorHex(#409400) imageName:@"已落后"];
    } else {
        [self.labelView setTitle:@"已领先" titleColor:UIColorHex(#FF2B34) imageName:@"已领先"];
    }
    
    // 获取当前时间
//    NSString *currentDateStr = [LLDateUtilis getCurrentTimeString];
//    // 距离开始时间差
//    NSDateComponents *diff = [LLDateUtilis compareFromDateString:currentDateStr toDateString:self.model.EndTime deteUnit:Hour | Minute | Second];
//    [self handleTimeEventWithComponents:diff];
//
    [self notifyAction];
    
    [self.timeBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.peopleLabel.mas_bottom).mas_offset(5);
    }];
    
    
}
// 购买
- (void)handleMyBuyAction
{
    self.labelView.hidden = YES;
    NSString *str = [NSString stringWithFormat:@"成交时间%@", self.model.PayTime];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
     [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[attr.string rangeOfAll]];
    [self.timeBtn setImage:nil forState:UIControlStateNormal];
    [self.timeBtn setAttributedTitle:attr forState:UIControlStateNormal];

    [self.timeBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.peopleLabel.mas_bottom).mas_offset(5);
    }];

}


//- (void)handleTimeEventWithComponents:(NSDateComponents *)diff
//{
//    self.model.hour = diff.hour >= 0 ? diff.hour : 0;
//    self.model.minute = diff.minute >= 0 ? diff.minute : 0;
//    self.model.second = diff.second >= 0 ? diff.second : 0;
//    // 总秒数
//    self.model.totalSecond = self.model.hour * 3600 + self.model.minute * 60 + self.model.second;
//
//    NSString *text = [NSString stringWithFormat:@"距离结束：%02ld:%02ld:%02ld", self.model.hour, self.model.minute, self.model.second];
//    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(DF2121) range:[attr.string rangeOfAll]];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[text rangeOfString:@"距离结束："]];
//    [self.timeBtn setAttributedTitle:attr forState:UIControlStateNormal];
//    if (self.model.timer == nil) {
//        YYWeakProxy *proxy = [YYWeakProxy proxyWithTarget:self];
//        self.model.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:proxy selector:@selector(timerAction) userInfo:nil repeats:YES];
//        [[NSRunLoop currentRunLoop] addTimer:self.model.timer forMode:NSRunLoopCommonModes];
//    }
//
//}
//
//- (void)timerAction
//{
//    self.model.totalSecond--;
//    if (self.model.totalSecond < 0) {
//        self.model.totalSecond = 0;
//    }
//
//    self.model.hour = self.model.totalSecond / 3600;
//    self.model.minute = self.model.totalSecond % 3600 / 60;
//    self.model.second = self.model.totalSecond % 3600 % 60;
//
//    NSString *text = [NSString stringWithFormat:@"距离结束：%02ld:%02ld:%02ld", self.model.hour, self.model.minute, self.model.second];
//    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(DF2121) range:[attr.string rangeOfAll]];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[text rangeOfString:@"距离结束："]];
//    [self.timeBtn setAttributedTitle:attr forState:UIControlStateNormal];
//
//}

///// 重用之前清楚计时器
//- (void)prepareForReuse
//{
//    [super prepareForReuse];
//    // 先清除定时器
//    [self.model.timer invalidate];
//    self.model.timer = nil;
//}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)setupSubviews
{
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.contentView);
        make.height.equalTo(@36);
    }];

    [self.leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView.mas_left).mas_offset(15);
        make.top.equalTo(self.topView.mas_bottom).mas_offset(10);
        make.width.height.equalTo(@83);
    }];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.leftImageView.mas_right).mas_offset(15);
        make.right.equalTo(self.contentView.mas_right).mas_offset(-8);
        make.top.equalTo(self.leftImageView);
    }];

    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(5);
        make.left.equalTo(self.titleLabel);
    }];
    
    [self.labelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.priceLabel.mas_right).mas_offset(10);
        make.centerY.equalTo(self.priceLabel);
        make.height.mas_equalTo(24);
    }];

    [self.peopleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.priceLabel.mas_bottom).mas_offset(5);
        make.left.right.equalTo(self.titleLabel);
    }];

    [self.timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.peopleLabel.mas_bottom).mas_offset(3);
        make.left.equalTo(self.titleLabel);
    }];

    [self.detailBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView.mas_right).mas_offset(-15);
        make.bottom.equalTo(self.contentView.mas_bottom).mas_offset(-10);
    }];

    [self.kefuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.detailBtn.mas_left).mas_offset(-20);
        make.bottom.equalTo(self.detailBtn);
    }];
}

- (TTRecyclingCellTopView *)topView
{
    if (!_topView) {
        _topView = [[TTRecyclingCellTopView alloc] init];
        [self.contentView addSubview:_topView];
    }
    return _topView;
}

- (UIImageView *)leftImageView
{
    if (!_leftImageView) {
        _leftImageView = [[UIImageView alloc] init];
        _leftImageView.contentMode = UIViewContentModeScaleAspectFill;
        _leftImageView.layer.cornerRadius = 8;
        _leftImageView.layer.masksToBounds = YES;
        [self.contentView addSubview:_leftImageView];
    }
    return _leftImageView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel labelWithTitle:@"" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:15]];
        _titleLabel.numberOfLines = 2;
        [self.contentView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)priceLabel
{
    if (!_priceLabel) {
        _priceLabel = [UILabel labelWithTitle:@"" color:UIColorHex(333333) fontSize:13];
        [self.contentView addSubview:_priceLabel];
    }
    return _priceLabel;
}

- (TTLeadingLabelView *)labelView
{
    if (!_labelView) {
        _labelView = [[TTLeadingLabelView alloc] init];
        [self.contentView addSubview:_labelView];
    }
    return _labelView;
}

- (UILabel *)peopleLabel
{
    if (!_peopleLabel) {
        _peopleLabel = [UILabel labelWithTitle:@"" color:UIColorHex(666666) fontSize:12];
        [self.contentView addSubview:_peopleLabel];
    }
    return _peopleLabel;
}


- (UIButton *)timeBtn
{
    if (!_timeBtn) {
        _timeBtn = [UIButton createButtonWithTitle:@"" titleColor:UIColorHex(333333) titleFont:[UIFont boldSystemFontOfSize:12] backgroundColor:nil target:nil action:nil];
        [self.contentView addSubview:_timeBtn];
    }
    return _timeBtn;
}

- (UIButton *)kefuBtn
{
    if (!_kefuBtn) {
        _kefuBtn = [UIButton createButtonWithTitle:@"联系客服" titleColor:UIColorHex(666666) titleFontSize:12 borderColor:UIColorHex(999999) cornerRadius:5 contentEdgeInsets:UIEdgeInsetsMake(3, 5, 3, 5) target:self action:@selector(kefuBtnClick)];
        [self.contentView addSubview:_kefuBtn];
    }
    return _kefuBtn;
}

- (UIButton *)detailBtn
{
    if (!_detailBtn) {
        _detailBtn = [UIButton createButtonWithTitle:@"查看详情" titleColor:UIColorHex(666666) titleFontSize:12 borderColor:UIColorHex(999999) cornerRadius:5 contentEdgeInsets:UIEdgeInsetsMake(3, 5, 3, 5) target:self action:@selector(detailBtnClick)];
        _detailBtn.enabled = NO;
        [self.contentView addSubview:_detailBtn];
    }
    return _detailBtn;
}



- (void)setFrame:(CGRect)frame
{
    frame.origin.x += 15;
    frame.size.width -= 30;
    frame.origin.y += 10;
    frame.size.height -= 10;

    [super setFrame:frame];
}


@end
